#include "MemoryStream.h"

void MemoryStream::get_index_next(uint16 length){
	mGetIndex=(mGetIndex+length)%mSize;
	if(mLength>length){
		mLength-=length;
	}
	else{
		mLength=0;
	}

}

void MemoryStream::put_index_next(uint16 length){
	mPutIndex=(mPutIndex+length)%mSize;
	if((mSize-mLength)>length){
		mLength+=length;
	}
	else{
		mLength=mSize;
	}
}


void MemoryStream::Flush(){
	uint16 mLength=0;
	uint16 mPutIndex=0;
	uint16 mGetIndex=0;
}

uint16 MemoryStream::GetSize(){
	return mSize;
}
uint16 MemoryStream::GetDataLength(){
	return mLength;
}

int16 MemoryStream::Peek(){
	int16 ret=0;
	if(mMemBuffer!=NULL){
		return mMemBuffer[mGetIndex];
	}
	return -1;
}

uint16 MemoryStream::PeekBytes(uint8* buffer,uint16 bufferSize,uint16 peekLength){
	uint16 ret=0;
	if(mMemBuffer!=NULL&&buffer!=NULL&&bufferSize>0&&peekLength>0){
		uint16 len=peekLength;
		len=len>bufferSize?bufferSize:len;
		len=len>mLength?mLength:len;
		for(int i=0;i<len;i++){
			buffer[i]=mMemBuffer[(mGetIndex+i)%mSize];
		}
		return len;
	}
	return ret;
}

int16 MemoryStream::Read(){
	int16 ret=Peek();
	if(ret>0){
		get_index_next(1);
	}
	return ret;
}

uint16 MemoryStream::ReadBytes(uint8* buffer,uint16 bufferSize,uint16 readLength){
	uint16 ret=PeekBytes(buffer,bufferSize,readLength);
	get_index_next(ret);
	return ret;
}

uint16 MemoryStream::Write(uint8 aByte){
	uint16 ret=0;
	if(mMemBuffer!=NULL){
		mMemBuffer[mPutIndex]=aByte;
		put_index_next(1);
		ret=1;
	}
	return ret;
}

uint16 MemoryStream::WriteBytes(uint8* buffer,uint16 writeLength){
	uint16 ret=0;
	if(mMemBuffer!=NULL&&buffer!=NULL>0&&writeLength>0){
		uint16 len=writeLength;
		len=len>(mSize-mLength)?(mSize-mLength):len;
		for(int i=0;i<len;i++){
			mMemBuffer[(mPutIndex+i)%mSize]=buffer[i];
		}
		put_index_next(len);
		return len;
	}
	return ret;
}

MemoryStream::MemoryStream(uint16 size){
	mMemBuffer=(uint8*)malloc(size);
	mSize=size;
	Flush();
}
MemoryStream::~MemoryStream(){
	if(mMemBuffer!=NULL){
		free(mMemBuffer);
		mMemBuffer=NULL;
	}
	Flush();
}